package com.asia.bomc.workflow.dao;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public abstract class AbstractBaseDao<T, PK> implements
		IBaseDao<T, PK> {

	private EntityManager em;

	@Override
	public void create(Object entity) {
		em.persist(entity);
	}

	@Override
	public void delete(Object entity) {
		em.remove(entity);
	}

	@Override
	public void update(T entity) {
		em.merge(entity);
	}

	@Override
	public T findById(Class<T> entityClass, PK pk) {
		return em.find(entityClass, pk);
	}

	@Override
	public List<T> findByJpql(Class<T> entityClass, String jpql,
			Map<String, Object> critals) {
		Query query = em.createQuery(jpql);
		if (critals != null) {
			for (String key : critals.keySet())
				query.setParameter(key, critals.get(key));
		}
		return query.getResultList();
	}

	public EntityManager getEntityManager() {
		return em;
	}

	@PersistenceContext(name="entityManagerFactory")
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

}
